<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="applicationRecordForm" :label-width="formLabelWidth" ref="applicationRecordFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="applicationRecordForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findEnterprise"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="招聘岗位名称" prop="jobDescriptionName">
              <el-input v-model="applicationRecordForm.jobDescriptionName" placeholder="请选择招聘岗位名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findJobDescription"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="应聘者姓名" prop="candidateName">
              <el-input v-model="applicationRecordForm.candidateName" placeholder="请选择应聘者姓名" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findCandidate"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-select v-model="applicationRecordForm.status" placeholder="请选择状态">
                <el-option label="申请" :value="10"></el-option>
                <el-option label="面试邀约" :value="20"></el-option>
                <el-option label="录用" :value="30"></el-option>
                <el-option label="拒绝" :value="90"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
    <el-dialog v-model="jobDescriptionSelectorVisible" v-if="jobDescriptionSelectorVisible" title="招聘岗位选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <job-description-selector @job-description-selected-event="handleJobDescriptionSelectedEvent">
      </job-description-selector>
    </el-dialog>
    <el-dialog v-model="candidateSelectorVisible" v-if="candidateSelectorVisible" title="应聘者基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <candidate-selector @candidate-selected-event="handleCandidateSelectedEvent">
      </candidate-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import applicationRecordApi from '@/api/applicationRecordApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {ApplicationRecordForm} from "@/types/req/applicationRecordForm";
import type {Result} from '@/types/result'
import type {ApplicationRecord} from "@/types/resp/applicationRecord";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";
import JobDescriptionSelector from "@/views/jobDescription/JobDescriptionSelector.vue";
import CandidateSelector from "@/views/candidate/CandidateSelector.vue";

const props = defineProps<Id>()
const applicationRecordFormRef = ref<FormInstance | null>(null);
const applicationRecordForm = reactive<ApplicationRecordForm>({
  enterpriseId: 0,
  enterpriseName: '',
  jobDescriptionId: 0,
  jobDescriptionName: '',
  candidateId: 0,
  candidateName: '',
  status: undefined,
})
const enterpriseSelectorVisible = ref<boolean>(false)
const jobDescriptionSelectorVisible = ref<boolean>(false)
const candidateSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetApplicationRecordAddEvent'): void;
  (e: 'closeApplicationRecordAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  jobDescriptionName: [
    { required: true, message: '请输入招聘岗位名称', trigger: 'blur' }
  ],
  candidateName: [
    { required: true, message: '请输入应聘者姓名', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请输入状态', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initApplicationRecordFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initApplicationRecordFormById = async (id: number) => {
  const resp: Result<ApplicationRecord> = await applicationRecordApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(applicationRecordForm, resp.data)
  }
}

const onReset = () => {
  if (applicationRecordFormRef.value) {
    applicationRecordFormRef.value.resetFields()
  }
  emit('resetApplicationRecordAddEvent')
}

const onSave = () => {
  if (!applicationRecordFormRef.value) {
    return
  }
  applicationRecordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await applicationRecordApi.save(applicationRecordForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeApplicationRecordAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && applicationRecordForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    applicationRecordForm.enterpriseId = selectedEnterprise['enterpriseId']
    applicationRecordForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}

const findJobDescription = () => {
  jobDescriptionSelectorVisible.value = true
}

const handleJobDescriptionSelectedEvent = (selectedJobDescription: any) => {
  jobDescriptionSelectorVisible.value = false
  if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription && applicationRecordForm.jobDescriptionId !== selectedJobDescription['jobDescriptionId']) {
    applicationRecordForm.jobDescriptionId = selectedJobDescription['jobDescriptionId']
    applicationRecordForm.jobDescriptionName = selectedJobDescription['jobDescriptionName']
  }
}

const findCandidate = () => {
  candidateSelectorVisible.value = true
}

const handleCandidateSelectedEvent = (selectedCandidate: any) => {
  candidateSelectorVisible.value = false
  if (selectedCandidate && 'candidateId' in selectedCandidate && applicationRecordForm.candidateId !== selectedCandidate['candidateId']) {
    applicationRecordForm.candidateId = selectedCandidate['candidateId']
    applicationRecordForm.candidateName = selectedCandidate['candidateName']
  }
}

const onBack = () => {
  emit('closeApplicationRecordAddEvent')
}
</script>

<style lang="scss">
</style>
